package xyz.yeidi.dao.impl;

import xyz.yeidi.dao.api.OrderDetailDao;
import xyz.yeidi.pojo.Food;
import xyz.yeidi.pojo.Orderdetail;
import xyz.yeidi.utils.ConnUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author JIP
 * @Date 2021-08-08 10:45
 * @Version 1.0
 * @Describe :
 */
public class OrderDetailDaoImpl implements OrderDetailDao {
    @Override
    public Integer addOrderDetail(Orderdetail orderdetail) throws Exception {
        String sql = "insert into orderdetail(orderId, foodId) values (?,?)";
        Connection conn = ConnUtils.getConnection();
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setObject(1,orderdetail.getOrderId());
        ps.setObject(2,orderdetail.getFoodId());
        int i = ps.executeUpdate();
        ConnUtils.close(ps);
        return i;
    }

    @Override
    public List<Food> getFoodsByOrderId(Integer orderId) throws Exception {
        String sql = "select f.foodId,f.foodName,f.foodImg,f.foodPrice from food f,orderdetail o where o.orderId = ? and o.foodId = f.foodId";
        Food food = null;
        List<Food> list = new ArrayList<>();
        Connection conn = ConnUtils.getConnection();
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setObject(1,orderId);
        ResultSet rs = ps.executeQuery();
        while(rs.next()){
            food = new Food();
            food.setFoodId(rs.getInt(1));
            food.setFoodName(rs.getString(2));
            food.setFoodImg(rs.getString(3));
            food.setFoodPrice(rs.getDouble(4));
            list.add(food);
        }
        return list;
    }
}
